import { Component, OnInit, Input } from '@angular/core';

import { ModalController, NavParams } from '@ionic/angular';

import { AppGlobalService } from "../../shared/service/app-global.service";
import { EventService } from '../../shared/service/event.service';
import { HttpService } from '../../shared/service/http.service';
import { MapBaiduService } from '../../shared/service/map.baiduapi';
declare var BMap;
declare let $: any;
@Component({
    selector: 'app-choose-city',
    templateUrl: './choose-city.component.html',
    styleUrls: ['./choose-city.component.scss']
})
export class ChooseCityComponent implements OnInit {

    constructor(
        private modalController: ModalController,
        private navParams: NavParams,
        private httpService: HttpService,
        private mapBaiduService: MapBaiduService,
        private appGlobalService: AppGlobalService,
        private eventService: EventService
    ) {
    }
    @Input() link: any = {};
    @Input() tagData: any = {};
    @Input() modalTitle = '选择城市';
    @Input() changeCityPosition = 1; // 点击城市之后是否切换城市 1为切换 0或其他不切换
    indexs: any = [];
    areaList: any = [];
    citys: any = {};
    key: string;      // 用于搜索结果
    currentCity: any;     // 当前城市
    target: number;
    currentCityTab: any;

    data: any;
    // tslint:disable-next-line:max-line-length
    groupCities = [{ c: [{ p: "bj1bj", i: 1101, n: "北京" }, { p: "bjibaoji", i: 6103, n: "宝鸡" }], l: "B" }, { c: [{ p: "cccc", i: 2201, n: "长春" }, { p: "cz2cz", i: 3204, n: "常州" }, { p: "cs1cs", i: 4301, n: "长沙" }, { p: "chq7cq", i: 5001, n: "重庆" }, { p: "cd4cd", i: 5101, n: "成都" }], l: "c" }, { c: [{ p: "dldl", i: 2102, n: "大连" }, { p: "dgdg", i: 4419, n: "东莞" }], l: "D" }, { c: [{ p: "esenshi", i: 4228, n: "恩施" }], l: "E" }, { c: [{ p: "fz1fz", i: 3501, n: "福州" }, { p: "fs1fs", i: 4406, n: "佛山" }], l: "F" }, { c: [{ p: "gz1ganzhou", i: 3607, n: "赣州" }, { p: "gz2gz", i: 4401, n: "广州" }, { p: "glguilin", i: 4503, n: "桂林" }, { p: "gy4gy", i: 5201, n: "贵阳" }], l: "G" }, { c: [{ p: "hebheb", i: 2301, n: "哈尔滨" }, { p: "hz1hz", i: 3301, n: "杭州" }, { p: "hfhf", i: 3401, n: "合肥" }, { p: "hz5huiz", i: 4413, n: "惠州" }, { p: "hkhk", i: 4601, n: "海口" }], l: "H" }, { c: [{ p: "jl1jl", i: 2202, n: "吉林" }, { p: "jj2jj", i: 3604, n: "九江" }, { p: "jn1jn", i: 3701, n: "济南" }], l: "J" }, { c: [{ p: "kmkm", i: 5301, n: "昆明" }], l: "K" }, { c: [{ p: "ly19linyi", i: 3713, n: "临沂" }, { p: "ly20ly", i: 4103, n: "洛阳" }, { p: "lz10liuzhou", i: 4502, n: "柳州" }, { p: "lz11lanzhou", i: 6201, n: "兰州" }], l: "L" }, { c: [{ p: "mmmaoming", i: 4409, n: "茂名" }, { p: "my1my", i: 5107, n: "绵阳" }], l: "M" }, { c: [{ p: "njnj", i: 3201, n: "南京" }, { p: "nbnb", i: 3302, n: "宁波" }, { p: "ncnc", i: 3601, n: "南昌" }, { p: "nnnn", i: 4501, n: "南宁" }], l: "n" }, { c: [{ p: "qzqz", i: 3505, n: "泉州" }, { p: "qd1qd", i: 3702, n: "青岛" }], "l": "Q" }, { c: [{ p: "sjzshijiazhuang", i: 1301, n: "石家庄" }, { p: "sy1sy", i: 2101, n: "沈阳" }, { p: "sh4sh", i: 3101, n: "上海" }, { p: "sz3suzhou", i: 3205, n: "苏州" }, { p: "smxsanmenxia", i: 4112, n: "三门峡" }, { p: "s1sz", i: 4403, n: "深圳" }, { p: "sy15sanya", i: 4602, n: "三亚" }], l: "S" }, { c: [{ p: "tj1tj", i: 1201, n: "天津" }, { p: "tytaiyuan", i: 1401, n: "太原" }], l: "T" }, { c: [{ p: "wx3wx", i: 3202, n: "无锡" }, { p: "wzwz", i: 3303, n: "温州" }, { p: "wh1wuhu", i: 3402, n: "芜湖" }, { p: "wfweifang", i: 3707, n: "潍坊" }, { p: "wh2weihai", i: 3710, n: "威海" }, { p: "wh4wh", i: 4201, n: "武汉" }], l: "W" }, { c: [{ p: "xz1xz", i: 3203, n: "徐州" }, { p: "xm1xm", i: 3502, n: "厦门" }, { p: "xfxy", i: 4206, n: "襄阳" }, { p: "xaxa", i: 6101, n: "西安" }, { p: "xy6xianyang", i: 6104, n: "咸阳" }], l: "X" }, { c: [{ p: "yt1yt", i: 3706, n: "烟台" }, { p: "yc6yc", i: 4205, n: "宜昌" }], l: "Y" }, { c: [{ p: "zz2zz", i: 4101, n: "郑州" }, { p: "zz3zhuzhou", i: 4302, n: "株洲" }, { p: "zh2zh", i: 4404, n: "珠海" }, { p: "zs2zs", i: 4420, n: "中山" }, { p: "zy3zy", i: 5203, n: "遵义" }], l: "Z" }];
    hotCities: any;
    submit: any;
    noStorage: any = false; // false 表示要存 true 不要存
    entryType: number; // add by andrew.wen for 3.6.0 数据地图新增选择城市按钮 100 时候搜索户型不显示当前城市
    showIcon = true;
    isPxw = false;
    isShow = false; // 显示区县

    // 页面变量
    tempResult: any;

    ngOnInit() {
        this.currentCity = JSON.parse(this.mapBaiduService.getStore('currentCityPosition'))
            ? JSON.parse(this.mapBaiduService.getStore('currentCityPosition'))
            : { name: '深圳', code: 4403 };
        this.data = this.navParams.data.value;
        this.noStorage = this.navParams.data.noStorage;
        this.entryType = this.navParams.data.entryType;
        this.getInitInfo();
        if (this.appGlobalService.clientType === 'pxw' || this.appGlobalService.clientType === 'js') {
            this.isPxw = true;
        }
        this.currentCityTab = this.currentCity.name;
    }

    getInitInfo() {
        const params = {
            pageId: this.data,
            params: (this.link && this.link.params) ? this.link.params : {},
            sessionId: localStorage.getItem('sessionId')
        };
        let pageData = {};
        this.hotCities = [];
        // 先使用默认值随后使用接口返回值
        this.currentCity = { center: { lng: 114.066112, lat: 22.548511 }, code: "4403", name: "深圳" };
        this.httpService.post('application/page', params, res => {
            if (res) {
                // tslint:disable-next-line:no-string-literal
                pageData = JSON.parse(res['script']);
                this.initializeItems(pageData);
            }
        });
    }

    initializeItems(cityData: any) {
        this.hotCities = cityData.views[0].tags[0].hotCities ? cityData.views[0].tags[0].hotCities.data : [];
        this.groupCities = cityData.views[0].tags[0].groupCities ? cityData.views[0].tags[0].groupCities.data : [];
        // tslint:disable-next-line:max-line-length
        this.currentCity = cityData.views[0].tags[0].currentCity
            && cityData.views[0].tags[0].currentCity.data.n ?
            cityData.views[0].tags[0].currentCity.data.n : this.currentCity;
        this.submit = cityData.views[0].tags[0].submit ? cityData.views[0].tags[0].submit : undefined;
        // 是否显示关闭按钮
        this.showIcon = cityData.titleBar.title.showIcon;
        // // 获取索引
    }


    /**
     * 匹配城市
     *
     * @param {*} ev
     * @memberof ChooseCityComponent
     */
    getItems(ev: any) {
        // 再次初始化
        this.initializeItems(this.tagData['data']);
        // 输入数据
        const val = ev.target.value;
        if (val && val.trim() !== '') {
            this.indexs.map(index => {
                // 根据名字或者拼音
                this.citys[index] = this.citys[index].filter(city => {
                    if (city['pinyin'] !== undefined && val.trim() !== undefined) {
                        return (city['name'].indexOf(val.trim()) > -1 || city['pinyin'].toLowerCase().indexOf(val.trim().toLowerCase()) > -1);
                    } else {

                    }
                });
            });
            // 索引
            this.indexs = this.indexs.filter(item => {
                return (this.citys[item].length > 0);
            });
        }
    }

    doDiss() {
        this.modalController.dismiss({});
    }

    checkCurrent(cityObj) {
        localStorage.setItem('position', JSON.stringify(cityObj));
        this.modalController.dismiss(cityObj);
    }

    focusInput() {
        // 隐藏当前城市
        $('#choose_current_city_label_id').fadeOut();
        $('#choose_current_city_id').fadeOut();
        $('#choose_hot_city_sec').fadeOut();
    }

    ionBlur() {
        $('#choose_current_city_label_id').fadeIn();
        $('#choose_current_city_id').fadeIn();
        $('#choose_hot_city_sec').fadeIn();
    }

    /**
     * 选择行
     *
     * @param {*} cityObj 选定的城市
     * @memberof ChooseCityComponent
     */
    doClose(cityObj?, type?) {
        if (type === 1) {
            cityObj.n = cityObj.name;
            cityObj.i = String(cityObj.code);
        }
        const searchName = cityObj.n;
        this.mapBaiduService.getPointByName(searchName, (point) => { // Fix bug-view-3842.html by andrew.wen
            if (this.submit.content.needChildren !== undefined) {
                this.noStorage = false;
            }
            if (this.submit && !this.noStorage) {
                // 经纬度改变 则刷新position
                const result = {
                    center:
                        { lng: point.lng, lat: point.lat },
                    name: cityObj.n,
                    code: cityObj.i,
                    district: '', // 2.0新增区域
                    address: '',
                    location: {}
                };
                const geoc = new BMap.Geocoder();
                const pt = new BMap.Point(point.lng, point.lat);
                geoc.getLocation(pt, rs => {
                    try {
                        // console.log('msg----->' + JSON.stringify(rs));
                        let poisLen = rs.surroundingPois.length - 1;
                        const poisDetail = rs.surroundingPois.length > 0 ? rs.surroundingPois[0].title : '';
                        result.address = rs.addressComponents.city
                            + poisDetail;
                        if (rs.addressComponents.district) {
                            result.district = rs.addressComponents.district;
                        }
                        // 返回同一个点则线上画矩形
                        if (poisLen === 0) {
                            // tslint:disable-next-line:max-line-length
                            rs.surroundingPois[1] = { point: { lng: rs.surroundingPois[0].point.lng + 0.05, lat: rs.surroundingPois[0].point.lat + 0.05 } };
                            poisLen = 1;
                        }
                        const begainLargeThanEnd = rs.surroundingPois[0].point.lat > rs.surroundingPois[poisLen].point.lat;
                        result.location = {
                            content: {
                                ll1: {
                                    // tslint:disable-next-line:max-line-length
                                    longitude: begainLargeThanEnd ? rs.surroundingPois[0].point.lng : rs.surroundingPois[poisLen].point.lng,
                                    // tslint:disable-next-line:max-line-length
                                    latitude: begainLargeThanEnd ? rs.surroundingPois[0].point.lat : rs.surroundingPois[poisLen].point.lat
                                },
                                ll2: {},
                                ll3: {},
                                ll4: {
                                    // tslint:disable-next-line:max-line-length
                                    longitude: begainLargeThanEnd ? rs.surroundingPois[poisLen].point.lng : rs.surroundingPois[0].point.lng,
                                    // tslint:disable-next-line:max-line-length
                                    latitude: begainLargeThanEnd ? rs.surroundingPois[poisLen].point.lat : rs.surroundingPois[0].point.lat
                                }
                            }
                        };
                        this.tempResult = result;
                    } catch (error) {
                        console.log('msg----->get address error ' + JSON.stringify(error));
                    } finally {

                        if (this.changeCityPosition !== undefined && this.changeCityPosition === 1) {
                            // callbackFunc();
                            localStorage.setItem('position', JSON.stringify(result));
                            // add by andrew.wen for 3.6.0 数据地图新增切换城市按钮
                            localStorage.setItem('mapPosition', JSON.stringify(result));
                        }
                        this.submit.content.code = cityObj.i;
                        this.submit.sessionId = localStorage.getItem('sessionId');
                        cityObj['center'] = this.tempResult.center;
                        // 铺铺旺新增临时需求
                        if (this.appGlobalService.clientType === 'ppw') {
                            document.getElementById('identityCityName').innerHTML = cityObj.n;
                        }
                        this.httpService.post('application/submit', this.submit, (data) => {
                            // tslint:disable-next-line:no-string-literal
                            if (data['success']) {
                                this.currentCityTab = cityObj.n;
                                this.areaList = data.data.data;
                                if (this.submit.content.needChildren !== undefined) {
                                    this.isShow = true;
                                }
                            }
                        });
                        // 判断是仅仅选址城市还是首页选址城市
                        if (this.submit.content.needChildren === undefined) {
                            this.modalController.dismiss(cityObj);
                        }
                    }
                });
            } else {
                const result = {
                    center:
                        { lng: point.lng, lat: point.lat },
                    name: cityObj.n,
                    code: cityObj.i,
                    address: '',
                    district: '', // 2.0新增区域
                    location: {}
                };
                if (this.entryType === 1) {
                    // 经纬度改变 则刷新position
                    const geoc = new BMap.Geocoder();
                    const pt = new BMap.Point(point.lng, point.lat);
                    geoc.getLocation(pt, rs => {
                        try {
                            // console.log('msg----->' + JSON.stringify(rs));
                            let poisLen = rs.surroundingPois.length - 1;
                            const poisDetail = rs.surroundingPois.length > 0 ? rs.surroundingPois[0].title : '';
                            result.address = rs.addressComponents.city
                                + poisDetail;
                            if (rs.addressComponents.district) {
                                result.district = rs.addressComponents.district;
                            }
                            // 返回同一个点则线上画矩形
                            if (poisLen === 0) {
                                // tslint:disable-next-line:max-line-length
                                rs.surroundingPois[1] = { point: { lng: rs.surroundingPois[0].point.lng + 0.05, lat: rs.surroundingPois[0].point.lat + 0.05 } };
                                poisLen = 1;
                            }
                            const begainLargeThanEnd = rs.surroundingPois[0].point.lat > rs.surroundingPois[poisLen].point.lat;
                            result.location = {
                                content: {
                                    ll1: {
                                        // tslint:disable-next-line:max-line-length
                                        longitude: begainLargeThanEnd ? rs.surroundingPois[0].point.lng : rs.surroundingPois[poisLen].point.lng,
                                        // tslint:disable-next-line:max-line-length
                                        latitude: begainLargeThanEnd ? rs.surroundingPois[0].point.lat : rs.surroundingPois[poisLen].point.lat
                                    },
                                    ll2: {},
                                    ll3: {},
                                    ll4: {
                                        // tslint:disable-next-line:max-line-length
                                        longitude: begainLargeThanEnd ? rs.surroundingPois[poisLen].point.lng : rs.surroundingPois[0].point.lng,
                                        // tslint:disable-next-line:max-line-length
                                        latitude: begainLargeThanEnd ? rs.surroundingPois[poisLen].point.lat : rs.surroundingPois[0].point.lat
                                    }
                                }
                            };
                        } catch (error) {
                            console.log('msg----->get address error ' + JSON.stringify(error));
                        } finally {
                            localStorage.setItem('mapPosition', JSON.stringify(result));
                            this.modalController.dismiss(result);
                        }
                    });
                } else {
                    if (this.submit.content.submit && this.submit.content.submit === "false") {
                        // 禁用submit
                    } else {
                        this.submit.content.code = cityObj.i;
                        this.submit.sessionId = localStorage.getItem('sessionId');
                        this.httpService.post('application/submit', this.submit, (data) => {
                            // tslint:disable-next-line:no-string-literal
                            if (data['success']) {
                                console.log('submit city code success ------->\n');
                            } else {
                            }
                        });
                    }

                    this.modalController.dismiss(cityObj);
                }
            }
        });
    }

    positionInfo() {
        // const cityPosition = JSON.parse(this.mapBaiduService.getStore('currentCityPosition'));
        // localStorage.setItem('position', JSON.stringify(cityPosition));
        // localStorage.setItem('mapPosition', JSON.stringify(cityPosition));
        this.mapBaiduService.onlyRefreshCurrentPositionAndCallBack(() => {
            // this.eventService.emit("getLocationDone", "true");
            // this.appGlobalService.reloadCurrentPage();
            console.log(new Date().toLocaleString() + '.' + new Date().getMilliseconds() + '  location success!	   ', '  	   ');
            this.modalController.dismiss();
        });

    }

    areaClick(item) {
        this.tempResult.district = item.name;
        const cityPosition = JSON.parse(this.mapBaiduService.getStore('mapPosition'));
        this.tempResult.code = item.code;
        const tempSearchName = this.tempResult.name + item.name;
        this.mapBaiduService.getPointByName(tempSearchName, (point) => {
            // localStorage.setItem('mapPosition', JSON.stringify(result));
            this.tempResult.center.lng = point.lng;
            this.tempResult.center.lat = point.lat;
            cityPosition.district = item.name;
            cityPosition.center.lng = point.lng;
            cityPosition.center.lat = point.lat;
            localStorage.setItem('mapPosition', JSON.stringify(cityPosition));
            this.modalController.dismiss(this.tempResult);
        });
    }
}
